//
//  HMStatusPictureView.swift
//  Weibo22
//
//  Created by Apple on 16/12/6.
//  Copyright © 2016年 Apple. All rights reserved.
//

import UIKit
import SDWebImage

//  重用标记
private let HMStatusPictureViewCellIdentifier = "HMStatusPictureViewCellIdentifier"
//  每项直接的间距
private let itemMargin: CGFloat = 5
//  计算每项的宽度
private let itemWidth = (ScreenWidth - 2 * StatusItemMargin - 2 * itemMargin) / 3
//  自定义首页配图视图
class HMStatusPictureView: UICollectionView {
    //  配图数据源
    var picUrls: [HMStatusPictureInfo]? {
        didSet {
            messageLabel.text = "\(picUrls?.count ?? 0)"
            //  计算配图大小
            calcSize(count: picUrls?.count ?? 0)
            
            //  重写加载数据
            reloadData()
            
        }
    }
    
    //  MARK: -- 懒加载
    private lazy var messageLabel: UILabel = {
    
        let label = UILabel(fontSize: 20, textColor: UIColor.red)
        label.text = "9"
        return label
    }()

    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        let flowLayout = UICollectionViewFlowLayout()
        //  设置大小
        flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        //  设置行间距
        flowLayout.minimumLineSpacing = itemMargin
        //  设置列间距
        flowLayout.minimumInteritemSpacing = itemMargin
        
        
        super.init(frame: frame, collectionViewLayout: flowLayout)
        setupUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    private func setupUI() {
        
        //  注册cell
        register(HMStatusPictureViewCell.self, forCellWithReuseIdentifier: HMStatusPictureViewCellIdentifier)
        
        //  设置数据源代理
        dataSource = self
        
        addSubview(messageLabel)
        
        
        
        messageLabel.snp_makeConstraints { (make) in
            make.center.equalTo(self)
        }
    
    }
    
    
    //  根据配图个数计算配图大小
    private func calcSize(count: Int) {
        
        
        if count == 1 {
            //  如果是单张图片,需要从本地加载下载的图片
            if let imageUrl = picUrls!.first!.thumbnail_pic {
                //  从本地加载下载的图片
                if let image = SDWebImageManager.shared().imageCache.imageFromDiskCache(forKey: imageUrl) {
                    
                    //  1. 一般服务端会把单张图片的大小给我们,设置配图大小, 建议让服务端去做
                    //  2. 根据产品的需求, 计算单张图片的大小以及图片过窄的处理
                    
                    
                    //  单张图片的大小
                    var imageSize = image.size
                    //  图片过窄处理
                    if imageSize.width < 80 {
                        //  设置图片的宽度
                        let imageWidth: CGFloat = 80
                        //  计算高度
                        var imageHeight = imageWidth / imageSize.width * imageSize.height
                        
                        //  过长处理
                        if imageHeight > 150 {
                            imageHeight = 150
                        }
                        
                        //  计算后的大小
                        imageSize = CGSize(width: imageWidth, height: imageHeight)
                    }
                    
                
                    //  单张图片的大小,已经获取到了, 根据单张图片配图的大小
                    self.snp_updateConstraints { (make) in
                        make.size.equalTo(imageSize)
                    }
                    
                    //  设置单张图片的条目的大小
                    let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
                    //  重写设置itemSize
                    flowLayout.itemSize = imageSize
                    
                    //  保证配图的大小和itemSize大小同步
                    self.layoutIfNeeded()
                    
                }
                
                
            }
            
            
            
            
            return
        }
        
        
      
        //  列数
        let cols = count > 3 ? 3: count
        //  行数
        let rows = (count - 1) / 3 + 1
        //  配图宽度
        let currentWidth = CGFloat(cols) * itemWidth + CGFloat(cols - 1) * itemMargin
        //  配图高度
        let currentHeight = CGFloat(rows) * itemWidth + CGFloat(rows - 1) * itemMargin
        
        //  配图的大小
        let currentSize = CGSize(width: currentWidth, height: currentHeight)
        
        //  添加配图大小约束
        
        self.snp_updateConstraints { (make) in
            make.size.equalTo(currentSize)
        }
        
        //  如果不是单张图片,需要设置成原始图片大小
        //  设置大小
        let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
        flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        //  保证配图的大小和itemSize大小同步
        self.layoutIfNeeded()

    }
    
    
    
    
    

}

//  MARK: -- UICollectionViewDataSource
extension HMStatusPictureView: UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return picUrls?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: HMStatusPictureViewCellIdentifier, for: indexPath) as! HMStatusPictureViewCell
        
        //  设置数据源
        cell.picInfo = picUrls![indexPath.item]
        
        return cell
    }
    

}


//  自定义配图cell
class HMStatusPictureViewCell: UICollectionViewCell {
    
    var picInfo: HMStatusPictureInfo? {
        didSet {
            
            if let imageUrl = picInfo?.thumbnail_pic {
                imageView.sd_setImage(with: URL(string: imageUrl), placeholderImage: UIImage(named: "timeline_image_placeholder"))
                
                
                if imageUrl.hasSuffix(".gif") {
                
                    //  表示是gif图片
                    gifImageView.isHidden = false
                } else {
                    //  不是不是gif图片
                    gifImageView.isHidden = true
                }
                
                
                
            }
        
        }
    }
    
    //  MARK: -- 懒加载
    private lazy var imageView: UIImageView = {
        let imageView = UIImageView(image: UIImage(named: "timeline_image_placeholder"))
        //  设置图片按照原始比例显示
        imageView.contentMode = .scaleAspectFill
        //  多余部分剪切掉
        imageView.clipsToBounds = true
        
        return imageView
    }()
    //  gif图片
    private lazy var gifImageView: UIImageView = UIImageView(image: UIImage(named: "timeline_image_gif"))
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //  添加控件设置约束
    private func setupUI() {
        contentView.addSubview(imageView)
        contentView.addSubview(gifImageView)
        
        imageView.snp_makeConstraints { (make) in
            make.edges.equalTo(contentView)
        }
        
        gifImageView.snp_makeConstraints { (make) in
            make.bottom.equalTo(imageView)
            make.trailing.equalTo(imageView)
        }
    
    }
    
    
}










